/**
 * WangSong 2009-10-2 数据源由RT改为SNR,数据服务器和后台总服务器是可以分离的
 */
package cn.biplam.back.services.snr;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import cn.biplam.back.jda.Jda;
import cn.biplam.common.bean.sqlengine.Sql;
import cn.biplam.common.client.DbResource;
import cn.biplam.common.interfaces.ServiceNameResolveServer;
import cn.biplam.common.wrapper.ErrorMessage;
import cn.biplam.common.wrapper.KvMap;
import cn.biplam.common.wrapper.sqlresult.SqlResult;

/**
 * 名称解析服务接口实现类
 * @author 	WangSong Mar 7, 2009 4:42:10 PM
 * @version 1.0
 */
public class ServiceNameResolveServerImpl extends UnicastRemoteObject implements ServiceNameResolveServer{

	private static final long serialVersionUID = 8766758021521332944L;
	private Lock mLock=new ReentrantLock();
	private int iCount=0;
	private static String tableName = "sys_services";
	
	/**
	 * 构造方法
	 * @throws RemoteException
	 */
	public ServiceNameResolveServerImpl() throws RemoteException {
		iCount++;
	}
    	
	/**
	 * 返回服务集合
	 * @throws ErrorMessage 
	 * @throws RemoteException
	 */
	public KvMap<String,String> getService() throws ErrorMessage{
		
		KvMap<String,String>  kvService = new KvMap<String,String>();
		this.addCount();
		try {
			//数据库操作对象
			DbResource mDbResource = new DbResource(DbResource.SNR);
			Jda mJda = new Jda(mDbResource);
			
			StringBuffer sql = new StringBuffer();
			sql.append(" select t.id,t.service_name,     ");
			sql.append("        t.service_ip,t.service_port,t.szfy_id ");
			sql.append("   from ");
			sql.append(tableName);
			sql.append(" t ");
			
			Sql mSql = new Sql(sql.toString());
			SqlResult sr = mJda.executeSelect(mSql);
			for(int i=0;i<sr.size();i++){
				kvService.put(sr.get(i,"service_name").toUpperCase(),
						                "rmi://"+sr.get(i,"service_ip")+":"+ 
						                sr.get(i,"service_port")+"/"+
						                sr.get(i,"service_name"));
			}
		}catch(ErrorMessage e){
			throw e;
		} catch (RuntimeException e) {
			throw new ErrorMessage(e);
		} finally {
			this.reduceCount();
		}
		return kvService;
	}
	
	public int getCount() throws RemoteException {
		return this.iCount;
	}

	private synchronized void addCount() {
		this.iCount++;
	}

	private synchronized void reduceCount() {
		this.iCount--;
	}

	public void lock() throws RemoteException {
		mLock.lock();
	}

	public boolean trylock() throws RemoteException {
		return mLock.tryLock();
	}

	public void unlock() {
		mLock.unlock();
	}
	
}
